'''Created on 2020年3月3日

@author: Administrator
'''
import os, sys
from pathlib import Path
import time

from flask import json

from common.public import *
from orm.model import ExpenseForm, User, Dept, db
from view.baseview import BaseView


class ExpenseFormView(BaseView):
    def __init__(self):
        pass

    def query(self, params):
        """根据条件取得列表，params：条件参数"""
        result=[]
        where_condition = True
        
        if params["keyword"]:
            likestr= "%"+params["keyword"] +"%"
            where_condition=(ExpenseForm.content ** likestr )
        # 取得部门管辖区域
        if params["userid"]:
            user = User.get(User.id == params["userid"])
            # 取得部门列表ID
            deptids = Dept.select(Dept.id).where(Dept.up_id==user.dept_id)
            if deptids:
                # 如果取到部门列表，说明是总经办部门人员
                pass
            else:
                # 如果取不到部门列表，说明是总经办部门以外人员
                leader = User.select().where(User.id==params["userid"]).first()
                ids = []
                if leader.isleader == COMMON_TRUE:
                    # 如果是主管
                    rows = User.select(User.id).where(User.leader_id==params["userid"])
                    for row in rows:
                        ids.append(row.id)
                    ids.append(params["userid"])
                else:
                    ids.append(params["userid"])
                where_condition=where_condition &(ExpenseForm.master.in_(ids) | ExpenseForm.agent.in_(ids) | ExpenseForm.approver.in_(ids) |
                                                  ExpenseForm.cashier.in_(ids) | ExpenseForm.bookkeeper.in_(ids))

        if params["personnel"]:
            where_condition=where_condition &(ExpenseForm.master.in_(params["personnel"]) | ExpenseForm.agent.in_(params["personnel"]) | ExpenseForm.approver.in_(params["personnel"]) |
                                              ExpenseForm.cashier.in_(params["personnel"]) | ExpenseForm.bookkeeper.in_(params["personnel"]))
        if params["status"]:
            where_condition=where_condition &(ExpenseForm.status.in_(params["status"]))
        if params["date"]:
            likestr= params["date"]
            where_condition=where_condition & ((ExpenseForm.createdate >= params["date"][0] + " 00:00:00") & (ExpenseForm.createdate <= params["date"][1] + " 23:59:59") )
        total = ExpenseForm.select().where(where_condition).count()
        rows = ExpenseForm.select().where(where_condition).order_by(ExpenseForm.createdate.desc()).paginate(int(params["pageNo"]), int(params["pagesize"]))
        print(rows)
        for row in rows:
            annexs=[]
            for annex in json.loads(row.annex):
                annexs.append({"name":annex,"url":API_EXPENSEFORM_ANNEX_DOWNLOAD +str(row.id) + "/" + annex})
            data = {
                "id":row.id,
                "createdate":str(row.createdate),
                "deptid":row.dept.id,
                "deptname":row.dept.name,
                "agentid":row.agent.id,
                "agent":row.agent.username,
                "masterid": row.master_id,
                "masterer": row.master.username,
                "masterstatus": row.master.username + "[" + row.masterstatus + "]",
                 "approverid":row.approver.id,
                "approver":row.approver.username,
                "approverstatus":row.approver.username +"[" + row.approverstatus + "]",
                "cashierid":row.cashier.id,
                "cashier":row.cashier.username,
               "cashierstatus":row.cashier.username +"[" + row.cashierstatus + "]",
                "bookkeeperid":row.bookkeeper.id,
                "bookkeeper":row.bookkeeper.username,
               "bookkeeperstatus":row.bookkeeper.username +"[" + row.bookkeeperstatus + "]",
                "expensetype":row.expensetype,
                "amount":row.amount,
                "content":row.content,
                "status":row.status,
                "memo": row.memo,
                "annex":annexs
             }
            result.append(data )
        return super().resultSet(200, "", result, total=total)
    
    @db.atomic()                   
    def add(self, params):
        """
        添加
        """
        ExpenseForm.create(
                createdate=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
                dept_id=params["deptid"],
                agent_id=params["agentid"],
                master_id=params["masterid"],
                approver_id=params["approverid"],
                cashier_id=params["cashierid"],
                bookkeeper_id=params["bookkeeperid"],
                amount=params["amount"],
                content=params["content"],
                expensetype=params["expensetype"],
                status=AUDIT_STATUS_WAITE,
                masterstatus=AUDIT_STATUS_WAITE,
                approverstatus=AUDIT_STATUS_WAITE,
                cashierstatus=AUDIT_STATUS_WAITE,
                bookkeeperstatus=AUDIT_STATUS_WAITE,
                annex='[]'
        )
        return super().resultSet(200, "添加成功", [])
        raise Exception("添加失败")         
    @db.atomic()                   
    def update(self, params):
        """
        更新
        """
        rec= ExpenseForm.get(ExpenseForm.id==params["id"])
        if int(params["userid"]) == params["masterid"] and rec.masterstatus == AUDIT_STATUS_WAITE:
            # 主管
            rec.masterstatus = AUDIT_STATUS_PASSED
        elif int(params["userid"]) == params["approverid"] and rec.approverstatus == AUDIT_STATUS_WAITE:
            # 审批人 1
            if rec.masterstatus==AUDIT_STATUS_PASSED:
                #如果主已审核
                rec.approverstatus=AUDIT_STATUS_PASSED
            else:
                #如果主管未审核
                return super().resultSet(201, "主管还未审核通过,您无法操作。", [])
        elif int(params["userid"]) == params["cashierid"] and rec.cashierstatus == AUDIT_STATUS_WAITE:
            # 出纳 2
            if rec.approverstatus==AUDIT_STATUS_PASSED:
                #如果出纳已审核
                rec.cashierstatus=AUDIT_STATUS_PASSED
            else:
                #如果出纳未审核
                return super().resultSet(201, "审批人还未审核通过,您无法操作。", [])
        elif int(params["userid"]) == params["bookkeeperid"] and rec.bookkeeperstatus == AUDIT_STATUS_WAITE:
            # 会计4
            if rec.cashierstatus==AUDIT_STATUS_PASSED:
                #如果出纳已审核
                rec.bookkeeperstatus=AUDIT_STATUS_PASSED
            else:
                #如果出纳未审核
                return super().resultSet(201, "出纳还未审核通过,您无法操作。", [])
        else:
            return super().resultSet(201, "审核失败", [])
        if rec.masterstatus == AUDIT_STATUS_PASSED \
            and rec.cashierstatus == AUDIT_STATUS_PASSED \
            and rec.approverstatus == AUDIT_STATUS_PASSED \
            and rec.bookkeeperstatus == AUDIT_STATUS_PASSED:
            # 如果都审核通过，状态改为已完成
            rec.status= AUDIT_STATUS_DONE
        rec.save()
        return super().resultSet(200, "审核成功", [])
        raise Exception("审核失败")

    @db.atomic()                   
    def updateAnnex(self, filename,expenseformid):
        """
        更新附件
        """
        rec= ExpenseForm.get(ExpenseForm.id==expenseformid)
        annex = json.loads(rec.annex)
        annex.append(filename)
        rec.annex = json.dumps(annex)
        rec.save()
        return super().resultSet(200, "更新成功", [])
        raise Exception("更新失败")
    
    @db.atomic()                   
    def updateAllAnnex(self, param):
        """
        更新附件
        """
        rec= ExpenseForm.get(ExpenseForm.id==param['expenseformid'])
        annex = []
        for file in param['filelist']:
            annex.append(file["name"])
        rec.annex = json.dumps(annex)
        rec.save()
        filename = UPLOAD_PATH +"/expenseform/annex/" + str(param['expenseformid']) +"/"+param['removefile']["name"]
        if Path(filename).exists():
            # 指定的目录或文件存在
            os.remove(filename)
        else:
            return super().resultSet(210, "文件不存在更新失败", [])
        return super().resultSet(200, "更新成功", [])
        raise Exception("更新失败")

    @db.atomic()                   
    def delete(self, params):
        """
        作废
        """
        rec= ExpenseForm.get(ExpenseForm.id==params['id'])
        if int(params["userid"]) == int(params["masterid"]):
            # 主管
            rec.masterstatus = AUDIT_STATUS_OVER
        elif int(params["userid"]) == int(params["approverid"]):
            # 审批人 1
            rec.approverstatus = AUDIT_STATUS_OVER
        elif int(params["userid"]) == int(params["cashierid"]):
            # 出纳 2
            rec.cashierstatus = AUDIT_STATUS_OVER
        elif int(params["userid"]) == int(params["bookkeeperid"]):
            # 会计4
            rec.bookkeeperstatus = AUDIT_STATUS_OVER
        # else:
        #     return super().resultSet(201, "作废失败", [])
        rec.memo = params["memo"]
        rec.status= AUDIT_STATUS_OVER
        rec.save()
        return super().resultSet(200, "作废成功", [])
        raise Exception("作废失败")

